package com.yonyou.metadata.unified.http;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.iuap.utils.HttpTookit;
import com.yonyou.iuap.utils.PropertyUtil;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.isvrequest.ISVRequest;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.isvrequest.ISVRequestBody;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.imeta.core.rest.AuthSdkUtils;
import org.imeta.core.rest.MetaContext;
import org.imeta.core.utils.MetadataPropertyUtil;
import org.imeta.spring.support.cache.UnifiedMetaProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.imeta.core.rest.OkHttpClientUtil.appendAppInfoParam;


public class HttpClientUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    private static ISVRequest isvRequest = AppContext.getBean(ISVRequest.class);

    static {
        try {
            URL url = Thread.currentThread().getContextClassLoader().getResource("application.properties");
            if(null != url){
                String path = url.getPath();
                PropertyUtil.setConfFileUrl(path);
            }
        }catch (Exception e){}
    }

    public static String doHttpRequest(String url, String method, Map<String, String> params) {
        String serverName = getMetadataApiUrl();
        if (StringUtils.isAnyEmpty(url, method)) {
            return null;
        }
        if (StringUtils.isEmpty(serverName) && Objects.nonNull(UnifiedMetaProperties.getInstance())) {
            serverName = UnifiedMetaProperties.getInstance().getMetadataApiUrl();
        }
        String requestUrl = serverName + url;
//        Map<String, String> headers = new HashMap<String, String>();
//        String result = null;
//        if (params==null || params.isEmpty()) {
//            requestUrl = appendAppInfoParam(requestUrl);
//        }
//        else {
//            params.put("fromApp",MetadataPropertyUtil.getApplicationName());
//        }
//        if (StringUtils.equalsIgnoreCase(method, "POST")) {
//            result = HttpTookit.doPost(requestUrl, params, headers);
//        } else if (StringUtils.equalsIgnoreCase(method, "GET")) {
//            result = HttpTookit.doGet(requestUrl, params, headers);
//        }
        if (InvocationInfoProxy.getYhtAccessToken()!=null && !InvocationInfoProxy.getYhtAccessToken().startsWith("btt")) {
            ISVRequestBody isvRequestBody = new ISVRequestBody();
            isvRequestBody.setUrl(requestUrl);
            isvRequestBody.setRequestMethod("IMetaHttpGet");
            isvRequestBody.setParams(params);
            Map<String, String> headers = new HashMap<>();
            String yhtAccessToken = InvocationInfoProxy.getYhtAccessToken();
            headers.put("yht_access_token", yhtAccessToken);
            isvRequestBody.setHeaders(headers);
            String result = isvRequest.doRequest(InvocationInfoProxy.getTenantid(), isvRequestBody);
            return result;
        }

        return AuthSdkUtils.doHttpRequest(requestUrl,method,params,null);
    }
    public static String doBaseApiRequest(String url, String method, Map<String, String> params) {
        String serverName = PropertyUtil.getPropertyByKey("baseapi.url");
        if (Objects.nonNull(MetaContext.getInstance()) && Objects.nonNull(MetaContext.getAppConfig().getProperty("baseapi.url"))) {
            serverName = MetaContext.getAppConfig().getProperty("baseapi.url");
        }
        if (StringUtils.isAnyEmpty(url, method)) {
            return null;
        }
        if (StringUtils.isEmpty(serverName) && Objects.nonNull(UnifiedMetaProperties.getInstance())) {
            serverName = UnifiedMetaProperties.getInstance().getMetadataApiUrl();
        }
        if (StringUtils.isEmpty(serverName)){
            return null;
        }
        String requestUrl = serverName + url;
//        Map<String, String> headers = new HashMap<String, String>();
//        String result = null;
//        if (StringUtils.equalsIgnoreCase(method, "POST")) {
//            result = HttpTookit.doPost(requestUrl, params, headers);
//        } else if (StringUtils.equalsIgnoreCase(method, "GET")) {
//            result = HttpTookit.doGet(requestUrl, params, headers);
//        }
        return AuthSdkUtils.doHttpRequest(requestUrl,method,params,null);
    }

    public static String doMetadataApiPost(String url, Object value) throws Exception {
        String serverName = getMetadataApiUrl();
        if (StringUtils.isAnyEmpty(serverName, url)) {

            return null;
        }
        return doPostJsonString(serverName + url, JSONObject.toJSONString(value));
    }

    private static String getMetadataApiUrl() {
        String serverName = MetadataPropertyUtil.getMetadataApiServer();
//        if (Objects.nonNull(MetaContext.getInstance()) && Objects.nonNull(MetaContext.getAppConfig().getProperty("metadata.api.url"))) {
//            serverName = MetaContext.getAppConfig().getProperty("metadata.api.url");
//        }
//        else {
//            serverName = PropertyUtil.getPropertyByKey("metadata.api.url");
//        }
//        if (StringUtils.isEmpty(serverName) && Objects.nonNull(UnifiedMetaProperties.getInstance())) {
//            serverName = UnifiedMetaProperties.getInstance().getMetadataApiUrl();
//        }
        if (StringUtils.isEmpty(serverName)){
            logger.error("从配置文件中没有获取到 metadata.api.url，请检查配置");
        }else {
            logger.debug("metadata.api.url:{}",serverName);
        }
        return serverName;
    }


    private static String doPostJsonString(String url, String jsonString) throws IOException {
//        HttpPost httpPost = new HttpPost(url);
//        CloseableHttpClient client = HttpClients.createDefault();
//        String respContent = null;
//        StringEntity entity = new StringEntity(jsonString, "utf-8");// 解决中文乱码问题
//        entity.setContentEncoding("UTF-8");
//        entity.setContentType("application/json");
//        httpPost.addHeader("local", InvocationInfoProxy.getLocale());
//        //httpPost.addHeader(key, screat);
//        httpPost.setEntity(entity);
//        HttpResponse resp = client.execute(httpPost);
//        int statusCode = resp.getStatusLine().getStatusCode();
//        if (statusCode == 200) {
//            HttpEntity httpEntity = resp.getEntity();
//            respContent = EntityUtils.toString(httpEntity, "UTF-8");
//        } else if (statusCode == 402) {
//            HttpEntity httpEntity = resp.getEntity();
//            respContent = EntityUtils.toString(httpEntity, "UTF-8");
//        }
        return AuthSdkUtils.post(url,jsonString,null);
    }

    public static String doHttpRequestWithJSON(String url, JsonObject json) throws Exception {
        String serverName = getMetadataApiUrl();
//		String appId = PropertyUtil.getPropertyByKey("metadata.appId");
//		String appScreate = PropertyUtil.getPropertyByKey("metadata.appScreate");
        if (StringUtils.isAnyEmpty(serverName, url)) {
            return null;
        }
        String requestUrl = serverName + url;
//		Map<String, String> screateMap = new HashMap<String, String>();
//		screateMap.put(appId, appScreate);
//		String screat = MetaTokenUtils.map2Token(screateMap);
        String result = httpPostWithJSON(requestUrl, json);
        return result;
    }

    /**
     * 支持http请求 json封装
     *
     * @param url
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     * @throws Exception
     */
    public static String httpPostWithJSON(String url, JsonObject json) throws Exception {
        return doPostJsonString(url, json.toString());
    }


}
